use std::{fs, error::Error}; // 其中的args函数会接受命令行参数


pub struct Config{
    query:String,
    filename:String
}
impl Config{
    pub fn new(args: &Vec<String>)-> Result<Config, &str> {
        if args.len()<3 {
            return Err("参数长度不足!");
        }
        let query = args[1].clone();
        let filename = args[2].clone();
        Ok(Config {query, filename})
    }
}

pub fn run(config:Config)->Result<(), Box<dyn Error>>{
    // 根据文件名称读取文件
    let content = fs::read_to_string(config.filename)?;
    for line in search(&config.query, &content) {
        println!("{}", line)
    }
    Ok(())
}

pub fn search<'a>(query:&str, content:&'a str)->Vec<&'a str>{
    let mut results = Vec::new();
    for line in content.lines() {
        if line.contains(query) {
            results.push(line);
        }
    }
    return results;
}


#[cfg(test)]
mod tests{
    use super::*;

    #[test]
    fn one_result(){
        let query = "duct";
        let content = "\
            Rust:
safe fast, productive
            Pick three
        asdlfkal";
        assert_eq!(vec!["safe fast, productive"], search(query, content));
    }
}